home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 603 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  66 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Help: How to initialize objects created by new class[x]
  5. Date: Fri, 05 Jan 1996 11:15:35 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <30ECFA47.446B9B3D@intellektik.informatik.th-darmstadt.de>
  8. References: <4cicd6$lsv@news.capitalnet.com>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b4 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. wingl@capitalnet.com wrote:
  16. > Let say I have the following class
  17. > My_class {
  18. >   public:
  19. >     int (int i=0) : a(i), b(i) {}
  20. >   private:
  21. >     int a, b;
  22. > }
  23. > For the following statement, default constructor is involved upon
  24. > the creation of the object.
  25. >            My_class* my_ptr= new My_class;
  26. > However,  if I use
  27. >                          My_class* my_ptr= new My_class[10];
  28. > to allocate 10 objects of class My_class, then C++ would not
  29. > call any constructor to do any initialization.  All the objects
  30. > allocated are not initializated at all.
  31. > I wonder what is the proper way to perform object initialization
  32. > whenever an array of objects are created?  As long as a constructor
  33. > is involved for each of the object in the array, I don't care if all the
  34. > objects are initializated the same or not.
  35. > If there is no way to get constructor to initialize an array of objects
  36. > upon creation.  Does that means one should not do so?
  37.  
  38. That's not true. The expression 'new My_class[10]' should call the 
  39. default-ctor of 'My_class' for each element.
  40. (I will assume the class looks like
  41.  
  42.         class My_class {
  43.           public:
  44.             My_class (int i=0) : a(i), b(i) {}
  45.           private:
  46.             int a, b;
  47.         };
  48.  
  49. ).
  50. The problems start when your class doesn't provide a default-ctor
  51. or you want to initialize elements of the array with different values.
  52. Here you are out of luck, because C++ doesn't provide an appropriate
  53. syntax. You'll have to use some hack like using the placement-new/delete
  54. operators.
  55.  
  56.     Enno
  57.